// ***********************************
// name：设置cookies字段
// purpose: 添加或者修改cookies某字段
function setCookie(cName, value, time) {
  let today = new Date().getTime();
  let cookieStr;

  if (typeof value == "object") {
    value = JSON.stringify(value);
  }

  if (time == "forever") {
    time = 24 * 365 * 100;
    let endDay = new Date(today + time * 60 * 60 * 1000);
    cookieStr = cName + "=" + value + ";" + "expires=" + endDay + ";";
  } else if (time < 0) {
    cookieStr =
      cName + "=" + value + ";" + "expires=Thu, 01 Jan 1970 00:00:00 UTC;";
  } else if (time) {
    let endDay = new Date(today + time * 60 * 60 * 1000);
    cookieStr = cName + "=" + value + ";" + "expires=" + endDay + ";";
  } else {
    cookieStr = cName + "=" + value + ";";
  }

  document.cookie = cookieStr + "path=/;";
}

// name：获取cookies字段
// purpose: 根据字段名获取cookies某字段
function getCookie(cName) {
  var result = "";
  if (document.cookie.length > 0) {
    let cStart = document.cookie.indexOf(cName + "=");
    if (cStart !== -1) {
      cStart = cStart + cName.length + 1;
      let cEnd = document.cookie.indexOf(";", cStart);
      if (cEnd === -1) {
        cEnd = document.cookie.length;
      }
      result = decodeURI(document.cookie.substring(cStart, cEnd));
    }
  }
  try {
    result = JSON.parse(result);
  } catch (err) {
    console.log(err);
  }
  return result;
}

/**
 * 删除cookie
 * @param name cookie的名称
 */
function delCookie(name) {
  setCookie(name, "", -1);
}

/*
		导出当前目录下所有文件 中的对象
	*/

function exportFileAsObject(files) {
  const obj = {};

  files.keys().forEach((key) => {
    var _key = key.replace(/(\.\/|\.js)/g, "");
    if (_key !== "index") {
      _key = _key.replace(/-/g, "");
      obj[_key] = files(key).default;
    }
  });
  return obj;
}
/*
		url传参拼接
	*/
function paramsSplice(url, data) {
  var result = url;
  if (typeof data == "object") {
    if (Array.isArray(data)) {
      result = result + "/" + data.join(",");
    } else {
      result = result + "?" + JSONToQuery(data);
    }
  } else {
    result = result + "/" + data;
  }
  return result;
}
/*
		 将json转为 url参数
	*/
function JSONToQuery(data) {
  try {
    var tempArr = [];
    for (var i in data) {
      var key = encodeURIComponent(i);
      var value = encodeURIComponent(data[i]);
      tempArr.push(key + "=" + value);
    }
    var urlParamsStr = tempArr.join("&");
    return urlParamsStr;
  } catch (err) {
    return "";
  }
}
/*
	  将 url参数转为 json
	*/
function QueryToJSON(str) {
  var obj = {};
  var arr1 = str.split("?");
  var arr2 = arr1[1].split("&");
  for (var i = 0; i < arr2.length; i++) {
    var res = arr2[i].split("=");
    obj[res[0]] = res[1];
  }
  return obj;
}

/*
	 文件下载
	 data 传入数据流
	 name 文件名
	 */

function downFile(data, name) {
  if (!data) {
    return;
  }
  // {type: 'application/vnd.ms-excel;charset=utf-8'}
  var blob = new Blob([data]);
  var url = window.URL.createObjectURL(blob);
  var aLink = document.createElement("a");
  aLink.style.display = "none";
  aLink.download = name || "demo";
  aLink.href = url;
  //aLink.setAttribute("数据模版", "数据模版.xls");
  document.body.appendChild(aLink);
  aLink.click();
}

function isPrimitiveValue(value) {
  if (
    typeof value === "string" ||
    typeof value === "number" ||
    value == null ||
    typeof value === "boolean" ||
    Number.isNaN(value)
  ) {
    return true;
  }
  return false;
}
function cloneObject(value) {
  return JSON.parse(JSON.stringify(value));
}
function cloneDeep(value) {
  // 判断拷贝的数据类型，如果为原始类型数据，直接返回其值
  if (isPrimitiveValue(value)) {
    return value;
  }
  // 定义一个保存引用类型的变量,根据 引用数据类型不同的子类型初始化不同的值，以下对象类型的判断和初始化可以根据自身功能的需要做删减。这里列出了所有的引用类型的场景。
  let result;
  if (typeof value === "function") {
    // result=value 如果复制函数的时候需要保持同一个引用可以省去新函数的创建，这里用eval创建了一个原函数的副本
    result = eval(`(${value.toString()})`);
  } else if (Array.isArray(value)) {
    result = [];
  } else if (value instanceof RegExp) {
    result = new RegExp(value);
  } else if (value instanceof Date) {
    result = new Date(value);
  } else if (value instanceof Number) {
    result = new Number(value);
  } else if (value instanceof String) {
    result = new String(value);
  } else if (value instanceof Boolean) {
    result = new Boolean(value);
  } else if (typeof value === "object") {
    result = new Object();
  }
  for (let key in value) {
    if (value.hasOwnProperty(key)) {
      try {
        result[key] = cloneObject(value[key]); //属性值为原始类型包装对象的时候，（Number,String,Boolean）这里会抛错，需要加一个错误处理，对运行结果没有影响。
      } catch (error) {
        // console.error(error)
      }
    }
  }
  return result;
}

/**
 * @description JS对象深度合并
 * @param {object} target 需要拷贝的对象
 * @param {object} source 拷贝的来源对象
 * @returns {object|boolean} 深度合并后的对象或者false（入参有不是对象）
 */
function mergeDeep(target = {}, source = {}) {
  target = cloneDeep(target);
  if (typeof target !== "object" || typeof source !== "object") return false;
  for (const prop in source) {
    if (!source.hasOwnProperty(prop)) continue;
    if (prop in target) {
      if (typeof target[prop] !== "object") {
        target[prop] = source[prop];
      } else if (typeof source[prop] !== "object") {
        target[prop] = source[prop];
      } else if (target[prop].concat && source[prop].concat) {
        target[prop] = target[prop].concat(source[prop]);
      } else {
        target[prop] = mergeDeep(target[prop], source[prop]);
      }
    } else {
      target[prop] = source[prop];
    }
  }
  return target;
}

// 数组去重
function removalDuplicate(dataList, byName) {
  var result = [];
  var tem = {};
  for (var i = 0; i < dataList.length; i++) {
    if (!tem[dataList[i][byName]]) {
      result.push(dataList[i]);
      tem[dataList[i][byName]] = 1;
    }
  }
  return result;
}
// 限制页码
function getPage(page, pageSize, total) {
  var pageMax = Math.ceil(total / pageSize);
  if (page > pageMax) {
    page = pageMax;
  }
  if (page < 1) {
    page = 1;
  }
  return page;
}

export {
  setCookie,
  getCookie,
  delCookie,
  exportFileAsObject,
  paramsSplice,
  JSONToQuery,
  QueryToJSON,
  downFile,
  cloneDeep,
  mergeDeep,
  removalDuplicate,
  getPage,
};
